const fs = require('fs');
const path = require('path');
const db = require('../db/index.js');
const crypto = require('crypto');
// 导入bcrypt加密中间件
const bcrypt = require('bcrypt');
const { send } = require('process');


// 上传头像
// 上传头像
exports.uploadAvatar = (req, res) => {
  try {
    // 检查是否有文件上传
    const file = req.files[0];
    if (!file) {
      return res.status(400).json({ error: 'No file uploaded' });
    }

    // 生成唯一标识
    const onlyId = crypto.randomUUID();
    let oldName = file.filename;
    let newName = Buffer.from(file.originalname, 'latin1').toString('utf8');

    // 重命名文件
    fs.renameSync(`./public/upload/${oldName}`, `./public/upload/${newName}`);

    // 插入数据库
    const sql = 'insert into image_table set ?';
    db.query(sql, {
      image_url: `http://127.0.0.1:3007/upload/${newName}`,
      onlyId
    }, (err, result) => {
      if (err) return res.cc(err);

      // 返回成功的响应
      res.status(200).json({
        onlyId,
        status: 0,
        url: `http://127.0.0.1:3007/upload/${newName}`,
        message: '上传成功',
        file: {
          url: `http://127.0.0.1:3007/upload/${newName}`,
          name: file.originalname,
          size: file.size,
          type: file.mimetype
        }
      });
    });
  } catch (error) {
    // 处理错误
    res.status(500).json({ error: 'Server error' });
  }
};


// 绑定账号 onlyid account url
exports.bindAccount = (req, res) => {
  const {
    account,
    onlyId,
    url
  } = req.body
  const sql = 'update image_table set account = ? where onlyId = ?'
  db.query(sql, [account, onlyId], (err, result) => {
    if (err) return res.cc(err)
    if (result.affectedRows == 1) {
      const sql1 = 'update users_table set image_url = ? where account = ?'
      db.query(sql1, [url, account], (err, result) => {
        if (err) return res.cc(err)
        res.send({
          status: 0,
          message: '修改成功'
        })
      })
    }
  })
}

// 获取用户信息 接收参数 id
// 获取用户信息 接收参数 id
exports.getUserInfo = (req, res) => {
  const sql = 'select * from users_table where id = ?';
  db.query(sql, req.body.id, (err, result) => {
    if (err) return res.cc(err);
    if (result.length === 0) {
      return res.send({
        status: 1,
        message: '用户不存在'
      });
    }
    result[0].password = ''; // 清空密码字段
    res.send(result[0]);
  });
}

// 修改姓名 接收参数 id name
exports.changeName = (req, res) => {
  const {
    id,
    name
  } = req.body
  const sql = 'update users_table set name = ? where id = ?'
  db.query(sql, [name, id], (err, result) => {
    if (err) return res.cc(err)
    res.send({
      status: 0,
      message: '修改成功'
    })
  })
}

// 修改性别 接收参数 id gender
exports.changeSex = (req, res) => {
  const {
    id,
    gender
  } = req.body
  const sql = 'update users_table set gender = ? where id = ?'
  db.query(sql, [gender, id], (err, result) => {
    if (err) return res.cc(err)
    res.send({
      status: 0,
      message: '修改成功'
    })
  })
}

// 修改邮箱 接收参数 id email
exports.changeEmail = (req, res) => {
  const {
    id,
    email
  } = req.body
  const sql = 'update users_table set email = ? where id = ?'
  db.query(sql, [email, id], (err, result) => {
    if (err) return res.cc(err)
    res.send({
      status: 0,
      message: '修改成功'
    })
  })
}

// 修改用户密码 先输入旧密码 oldPassword 新密码 newPassword id 
exports.changePassword = (req, res) => {
  const { id, newPassword } = req.body;

  // 检查是否提供了新密码
  if (!newPassword) {
    return res.status(400).json({ error: '新密码是必填项' });
  }

  // 使用 bcrypt 加密新密码
  const hashedNewPassword = bcrypt.hashSync(newPassword, 10);

  // 更新数据库中的密码
  const sql = 'UPDATE users_table SET password = ? WHERE id = ?';
  db.query(sql, [hashedNewPassword, id], (err, result) => {
    if (err) return res.cc(err);

    res.send({
      status: 0,
      message: '修改成功'
    });
  });
};



// 重置密码
exports.updatePasswordWithVerification = (req, res) => {
  const {
    account,
    email,
    newPassword,
  } = req.body;

  // 验证账户和邮箱是否一致
  const verifySql = 'SELECT * FROM users_table WHERE account = ?';
  db.query(verifySql, account, (err, result) => {
    if (err) return res.cc(err);

    if (result.length === 0) {
      return res.send({
        status: 1,
        message: '账户不存在'
      });
    }

    // 修改密码
    const hashedPassword = bcrypt.hashSync(newPassword, 10);
    const updateSql = 'UPDATE users_table SET password = ? WHERE account = ?';
    db.query(updateSql, [hashedPassword, account], (err, updateResult) => {
      if (err) return res.cc(err);

      res.send({
        status: 0,
        message: '更新成功'
      });
    });
  });
};

// ----------------------------------------用户管理
// 添加管理员
exports.createAdmin = (req, res) => {
  const {
    account,
    name,
    gender,
    department,
    email,
    identity
  } = req.body
  // 判断账号是否存在与数据库中
  const sql = 'select * from users_table where account = ?'
  db.query(sql, account, (err, results) => {
    // 判断账号是否存在
    if (results.length < 0) {
      return res.send({
        status: 1,
        message: '账号不存在'
      })
    }
    if (results[0].status === 1) {
      return res.send({
        status: 1,
        message: '账号处于冻结状态，无法设置为管理员'
      })
    }
    const sql1 = 'update users_table set ? where account = ?'
    const createAt = new Date()
    const userInfo = {
      account,
      name,
      gender,
      department,
      email,
      // 身份
      identity,
      // 创建时间
      createAt,
      // 初始未冻结状态为0
      status: 0,
    }
    db.query(sql1, [userInfo, userInfo.account], (err, results) => {
      if (results.affectedRows !== 1) {
        return res.send({
          status: 1,
          message: '添加管理员失败'
        })
      }
      res.send({
        status: 0,
        message: '添加管理员成功'
      })
    })
  })
}

// 获取管理员列表 参数是 identity 
exports.getAdminList = (req, res) => {
  const sql = 'select * from users_table where identity = ?'
  db.query(sql, req.body.identity, (err, result) => {
    if (err) return res.cc(err)
    result.forEach((e) => {
      e.password = ''
      e.createAt = ''
      e.image_url = ''
      e.status = ''
    })
    res.send(result)
  })
}
// 编辑管理员账号信息
exports.editAdmin = (req, res) => {
  const {
    id,
    name,
    gender,
    email,
    department
  } = req.body
  const date = new Date()
  const sql0 = 'select department from users_table where id = ?'
  db.query(sql0, id, (err, result) => {
    const updateContent = {
      id,
      name,
      gender,
      email,
      department,
      updateAt: date,
    }
    const sql = 'update users_table set ? where id = ?'
    db.query(sql, [updateContent, updateContent.id], (err, result) => {
      if (err) return res.cc(err)
      res.send({
        status: 0,
        message: '修改管理员信息成功'
      })
    })
    // }
  })

}

// 对管理员取消赋权 参数 id
exports.changeIdentityToUser = (req, res) => {
  const identity = '用户'
  const sql = 'update users_table set identity = ? where id = ?'
  db.query(sql, [identity, req.body.id], (err, result) => {
    if (err) return res.cc(err)
    res.send({
      status: 0,
      message: '降级成功'
    })
  })
}

// 对用户进行赋权 参数 id identity
exports.changeIdentityToAdmin = (req, res) => {
  const date = new Date()
  const sql = 'update users_table set identity = ?,updateAt = ? where id = ?'
  db.query(sql, [req.body.identity, date, req.body.id], (err, result) => {
    if (err) return res.cc(err)
    res.send({
      status: 0,
      message: '赋权成功'
    })
  })
}

// 通过账号对用户搜索 account identity
exports.searchUser = (req, res) => {
  const { account, identity } = req.body;
  // and identity = ?
  const sql = 'select * from users_table where account = ? ';
  db.query(sql, [account], (err, result) => {
    if (err) return res.cc(err);
    result.forEach((e) => {
      e.password = '';
      e.createAt = '';
      e.image_url = '';
      e.status = '';
    });
    res.send(result);
  });
};

// 通过部门对用户搜索 department
exports.searchUserByDepartment = (req, res) => {
  const sql = 'select * from users_table where department = ? and identity = "用户"'
  db.query(sql, req.body.department, (err, result) => {
    if (err) return res.cc(err)
    result.forEach((e) => {
      e.password = ''
      e.image_url = ''
    })
    res.send(result)
  })
}


// 冻结用户 通过id 把status 置为 1 
exports.banUser = (req, res) => {
  const status = 1
  const sql = 'update users_table set status = ? where id = ?'
  db.query(sql, [status, req.body.id], (err, result) => {
    if (err) return res.cc(err)
    res.send({
      status: 0,
      message: '冻结成功'
    })
  })
}



// 解冻用户
exports.hotUser = (req, res) => {
  const status = 0
  const sql = 'update users_table set status = ? where id = ?'
  db.query(sql, [status, req.body.id], (err, result) => {
    if (err) return res.cc(err)
    res.send({
      status: 0,
      message: '解冻成功'
    })
  })
}

// 获取冻结用户列表
exports.getBanList = (req, res) => {
  const sql = 'select * from users_table where status = "1" '
  db.query(sql, (err, result) => {
    if (err) return res.cc(err)
    res.send(result)
  })
}

// 删除用户 id account
exports.deleteUser = (req, res) => {
  const sql = 'delete from users_table where id = ?'
  db.query(sql, req.body.id, (err, result) => {
    if (err) return res.cc(err)
    const sql1 = 'delete from image_table where account = ?'
    db.query(sql1, req.body.account, (err, result) => {
      if (err) return res.cc(err)
      res.send({
        status: 0,
        message: '删除用户成功'
      })
    })
  })
}

// 获取对应身份的一个总人数 identity
exports.getAdminListLength = (req, res) => {
  const sql = 'select * from users_table where identity = ? '
  db.query(sql, req.body.identity, (err, result) => {
    if (err) return res.cc(err)
    res.send({
      length: result.length
    })
  })
}

// 监听换页返回数据 页码 pager identity
// limit 10 为我们要拿到数据 offset 我们跳过多少条数据
exports.returnListData = (req, res) => {
  const number = (req.body.pager - 1) * 10
  const sql = `select * from users_table where identity = ? ORDER BY createAt limit 10 offset ${number} `
  db.query(sql, req.body.identity, (err, result) => {
    if (err) return res.cc(err)
    res.send(result)
  })
}



